package pt.ipleiria.plp;

import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import pt.ipleiria.plp.stub.MediaReader;

/**
 *  Class for images in URL format returned by the webservice
 * @author Filipe Felisberto e Ricardo Silva
 */
public class ImageURL extends Image {

    private String url;

    public ImageURL(String title, String description, String mediaType, String url) {
        super(title, description, mediaType);

        this.url = url;

    }

    public ImageURL(MediaReader mr) {
        super(mr.getTitle(), mr.getDescription(),mr.getMediaType());
        this.url =  mr.getUrl();
    }

    /**
     * @return the URL
     */
    public String getURL() {
        return url;
    }

    public byte[] getImageByte() throws Exception {

        HttpConnection c = (HttpConnection) Connector.open(getURL());
        int status = c.getResponseCode();

        if (status != 200) {
            throw new IOException("HTTP Response code = " + status);

        }


        int lenth = (int) c.getLength();
        System.out.println("Length: " + lenth);
        String type = getMediaType();
        System.out.println("Type: " + type);
        if (!type.equals("image/png") && !type.equals("image/jpeg")) {
            throw new IOException("Expecting image, received " + type);
        }

        if (lenth > 0) {
            DataInputStream is = c.openDataInputStream();

            byte[] data = new byte[lenth];
            is.readFully(data);

            return data;
        } else {
            throw new IOException("Content length is missing");
        }
    }
}
